package com.ljm.commom.web.filter;

import com.ljm.commom.web.http.BodyReaderRequestWrapper;
import com.ljm.commom.web.utils.IpUtils;
import com.ljm.common.constants.LogConstants;
import com.ljm.common.constants.ShiroConstants;
import com.ljm.common.util.IPUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.UUID;

/**
 * 版权：    Copyright by ljm
 * 描述：
 * 修改人：  HuamingChen
 * 修改时间：2020/3/6
 * 跟踪单号：
 * 修改单号：
 * 修改内容：
 */
public class BodyReaderRequestFilter implements Filter {
    private final static Logger logger= LoggerFactory.getLogger(BodyReaderRequestFilter.class);
    @Override
    public void init(FilterConfig filterConfig){

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest= (HttpServletRequest) servletRequest;
        BodyReaderRequestWrapper bodyReaderRequestWrapper = new BodyReaderRequestWrapper(httpServletRequest);
        // 增加traceId,方便日志跟踪
        String trackId= UUID.randomUUID().toString();
        MDC.put(LogConstants.LOG_TRACE_ID, trackId);
        LogConstants.trackIdThreadLocal.set(trackId);
        LogConstants.ipThreadLocal.set(IpUtils.getIpAddr(httpServletRequest));
        MDC.put(LogConstants.LOG_IP, IPUtils.getLocalIpAddress());
        httpServletRequest.getSession().getAttributeNames();
        String loginName=httpServletRequest.getSession().getAttribute(ShiroConstants.CURRENT_LOGIN_NAME)!=null?httpServletRequest.getSession().getAttribute(ShiroConstants.CURRENT_LOGIN_NAME).toString():"anonymous";
        logger.info("{}-{}-request-{}",loginName, LocalDateTime.now(),httpServletRequest.getRequestURI());
        filterChain.doFilter(bodyReaderRequestWrapper,servletResponse);
    }

    @Override
    public void destroy() {

    }
}
